#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>   // open
#include <unistd.h>  // write
#include <string.h>  // strlen
#include "../lzop.h"

#define BUFSIZE 1024

int main(int argc, char** argv) {
  lzop_stream s;
  unsigned char inbuf[BUFSIZE];
  unsigned char outbuf[BUFSIZE*2];
  int ofd, num, tmp;

  init_lzop_stream(&s);
  snprintf(inbuf, BUFSIZE, "Input string input string input string input string\n");

  ofd = open("testing.1", O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  if( ofd < 0 ) {
    fprintf(stderr, "Error opening file for writing!\n");
    return 1;
  }

  // first, write magic number
  num = bwrite_lzop_magic(outbuf, sizeof(outbuf));
  if( 0 == num ) {
    fprintf(stderr,"Error getting magic number\n");
    return 2;
  }
  if( write(ofd, outbuf, num) != num ) {
    fprintf(stderr, "Error writing file header!\n");
    return 3;
  }

  num = bwrite_lzop_header(&s, outbuf, sizeof(outbuf));
  if( 0 == num ) {
    lzop_perror(&s, NULL);
    return 2;
  }
  if( write(ofd, outbuf, num) != num ) {
    fprintf(stderr, "Error writing file header!\n");
    return 3;
  }

  num = lzop_compress(&s, inbuf, strlen(inbuf), outbuf, BUFSIZE*2);
  if( 0 == num ) {
    lzop_perror(&s, NULL);
    fprintf(stderr,"\n");
    return 4;
  }
  tmp = write(ofd, outbuf, num);
  if( tmp != num ) {
    fprintf(stderr, "Error writing block: %d != %d\n", tmp, num);
    return 5;
  }
  write(ofd, outbuf, num);
  write(ofd, outbuf, num);

  // last block is a 32bit unsigned int with value of zero,
  // meaning an empty block
  memset(outbuf, '\0', 4);
  write(ofd, outbuf, 4);

  close(ofd);

  return 0;
}
